package com.bjbn.config;

import com.bjbn.service.impl.FidsT3DeviceServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.context.annotation.Configuration;

import javax.annotation.PreDestroy;
import java.util.concurrent.ExecutorService;

/**
 * 优雅关闭配置类
 */
@Slf4j
@Configuration
public class GracefulShutdownConfig implements ApplicationRunner {

    @Autowired
    private FidsT3DeviceServiceImpl deviceService;

    /**
     * 应用关闭时的清理工作
     */
    @PreDestroy
    public void shutdown() {
        try {
            log.info("应用开始执行关闭操作...");
            
            // 关闭线程池
            if (deviceService != null) {
                ExecutorService executorService = getExecutorServiceFromReflection(deviceService);
                if (executorService != null) {
                    log.info("正在关闭线程池...");
                    executorService.shutdown();
                    // 等待一段时间让线程池中的任务完成
                    boolean terminated = executorService.awaitTermination(30, java.util.concurrent.TimeUnit.SECONDS);
                    if (!terminated) {
                        log.warn("线程池在等待时间内未完全关闭，强制关闭...");
                        executorService.shutdownNow();
                    } else {
                        log.info("线程池已成功关闭");
                    }
                }
            }
            
            log.info("应用关闭操作执行完成");
        } catch (Exception e) {
            log.error("应用关闭过程中发生异常", e);
        }
    }

    /**
     * 通过反射获取线程池实例
     */
    private ExecutorService getExecutorServiceFromReflection(Object service) {
        try {
            java.lang.reflect.Field field = service.getClass().getDeclaredField("processExecutor");
            field.setAccessible(true);
            return (ExecutorService) field.get(service);
        } catch (Exception e) {
            log.error("获取线程池实例失败", e);
            return null;
        }
    }

    @Override
    public void run(ApplicationArguments args) throws Exception {
        log.info("应用启动完成，添加了优雅关闭钩子");
    }
}